﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CodeBuilder.ServiceReference;
using CodeBuilder.Controls;

namespace CodeBuilder
{
    public partial class MainForm : UserControl
    {
        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                InitTreeTable();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 刷新树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_Refresh_Click(object sender, EventArgs e)
        {
            InitTreeTable();
        }

        #region 树绑定
        private void InitTreeTable()
        {
            treeTable.Nodes.Clear();

            //创建数据库表
            TreeNode tablesRoot = new TreeNode();
            tablesRoot.Text = "表";
            tablesRoot.Tag = new TreeViewTag(TreeViewType.表根, null);

            //创建视图
            TreeNode viewsRoot = new TreeNode();
            viewsRoot.Text = "视图";
            viewsRoot.Tag = new TreeViewTag(TreeViewType.视图根, null);

            //创建存储过程
            TreeNode procsRoot = new TreeNode();
            procsRoot.Text = "存储过程";
            procsRoot.Tag = new TreeViewTag(TreeViewType.存储过程根, null);

            treeTable.Nodes.Add(tablesRoot);
            treeTable.Nodes.Add(viewsRoot);
            treeTable.Nodes.Add(procsRoot);

            CreateObjects(tablesRoot,ObjectType.Table);
            CreateObjects(viewsRoot, ObjectType.View);
            CreateObjects(procsRoot, ObjectType.StoredProcedure);
        }

         /// <summary>
        /// 创建TreeView数据库表
        /// </summary>
        /// <param name="node"></param>
        private void CreateObjects(TreeNode node,ObjectType type)
        {
            DataBaseClient service = ServiceHost.Instance;
            List<Table> items =  service.GetObjects(type);
            IOrderedEnumerable<Table> tabs = items.OrderBy(t => t.Name);
            foreach (Table item in tabs)
            {
                TreeNode childNode = new TreeNode();                
                childNode.Text = string.Format("{0} {1}", item.Name,string.IsNullOrEmpty(item.Description) ? string.Empty : string.Format("[{0}]", item.Description));
                node.Nodes.Add(childNode);
                if (type == ObjectType.Table)
                {
                    childNode.Tag = new TreeViewTag(TreeViewType.表, item);
                    CreateTableColumns(childNode, item.Name);
                }
                else if (type == ObjectType.StoredProcedure)
                {
                    childNode.Tag = new TreeViewTag(TreeViewType.存储过程, item);
                    CreateProcParam(childNode, item.Name);
                }
                else if (type == ObjectType.View)
                {
                    childNode.Tag = new TreeViewTag(TreeViewType.视图, item);
                    CreateViewColumns(childNode, item.Name);
                }
            }
        }

        private void CreateTableColumns(TreeNode node, string tableName)
        {
            DataBaseClient service = ServiceHost.Instance;
            List<Column> columns = service.GetColumns(tableName);
            foreach (Column col in columns)
            {
                TreeNode childNode = new TreeNode();
                childNode.Tag = new TreeViewTag(TreeViewType.列, col);
                childNode.Text = string.Format("{0} {1}", col.Name, string.Format("[{0}  {1}]", col.DataTypeName, col.Description));
                node.Nodes.Add(childNode);
            }
        }

        /// <summary>
        /// View Column
        /// </summary>
        /// <param name="node"></param>
        /// <param name="tableName"></param>
        private void CreateViewColumns(TreeNode node,string viewName)
        {
            DataBaseClient service = ServiceHost.Instance;
            List<Column> columns = service.GetViewColumns(viewName);
            foreach (Column col in columns)
            {
                TreeNode childNode = new TreeNode();
                childNode.Tag = new TreeViewTag(TreeViewType.列, col);           
                childNode.Text = string.Format("{0} {1}", col.Name, string.Format("[{0}  {1}]", col.DataTypeName,col.Description));
                node.Nodes.Add(childNode);
            }
        }

        private void CreateProcParam(TreeNode node,string procName)
        {
            DataBaseClient service = ServiceHost.Instance;
            List<StoredProcedureParam> items = service.GetParas(procName);
            foreach (StoredProcedureParam item in items)
            {
                TreeNode childNode = new TreeNode();
                childNode.Tag = new TreeViewTag(TreeViewType.存储过程参数, item);      
                childNode.Text = string.Format("{0} {1}", item.ParameterName, string.Format("[{0}]", item.SqlDbType));
                node.Nodes.Add(childNode);
            }
        }

        /// <summary>
        /// 树单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeTable_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null && e.Node.Tag!=null)
            {
                TreeViewTag tag = (TreeViewTag)e.Node.Tag;
                if (tag.Type == TreeViewType.表)
                {
                    DataBaseClient service = ServiceHost.Instance;
                    List<Column> columns = service.GetColumns(((Table)tag.Object).Name); 
                    //单击的是表 
                    InitColumnsInGrid(columns, (Table)tag.Object);
                }
                else if (tag.Type == TreeViewType.视图)
                {
                    DataBaseClient service = ServiceHost.Instance;
                    List<Column> columns = service.GetViewColumns(((Table)tag.Object).Name);
                    //单击的是表 
                    InitColumnsInGrid(columns, (Table)tag.Object);
                }
            }
        }

        private void InitColumnsInGrid(List<Column> columns,Table tab)
        {
                      
            dgvColumns.AutoGenerateColumns = false;
            dgvColumns.DataSource = columns;
            dgvColumns.Tag = tab;
        }
        #endregion
       
        private List<Column> GetCurrentColumns()
        {
            List<Column> columns = (List<Column>)dgvColumns.DataSource;
            if (columns == null)
            {
                MessageBox.Show("请先选择左边的数据表！");
                return new List<Column>(0);
            }
            for (int i = 0; i < columns.Count; i++)
            {
                //是否作为条件
                //ColumnWhere
                columns[i].IsWhere = (bool)dgvColumns["Column_Where", i].Value;

                //是否选择
                //ColumnSelect
                columns[i].IsSelect = (bool)dgvColumns["Column_Select", i].Value;
            }
            return columns;
        }

        private Table GetCurrentTable()
        {
            Table tab = (Table)dgvColumns.Tag;
            if (tab == null)
            {
                MessageBox.Show("请先选择左边的数据表！");
                return new Table();
            }
            return tab;
        }

        private void SetColumnState(bool isSelect, bool isWhere)
        {
            List<Column> columns = GetCurrentColumns();
            for (int i = 0; i < columns.Count; i++)
            {
                if (isWhere)
                {
                     //ColumnWhere
                    columns[i].IsWhere = checkBox_Set_Where.Checked;
                }
                if (isSelect)
                {
                    columns[i].IsSelect = checkBox_Set_Select.Checked;
                }
            }

            //重新绑定   
            dgvColumns.AutoGenerateColumns = false; 
            dgvColumns.DataSource = columns;
            dgvColumns.Refresh();
        }

        /// <summary>
        /// 单选或者权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBoxSet_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkBox = (CheckBox)sender;
            if (checkBox != null && checkBox.Tag != null)
            {
                switch (checkBox.Tag.ToString().ToLower())
                {
                    case "select":
                        SetColumnState(true, false);
                        break;
                    case "where":
                        SetColumnState(false, true);
                        break;
                    default:
                        break;
                }
            }
        }

        /// <summary>
        /// 生成代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                BeginCreateCode();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void BeginCreateCode()
        {
            ClearTabPage();            

            List<Column> columns = GetCurrentColumns();
            if (columns != null && columns.Count > 0)
            {
                InitCodeCreate(columns, GetCurrentTable());
            }
            CreateCode();
        }

        /// <summary>
        /// 创建All Model,All Proc等
        /// </summary>
        private void CreateCode()
        {
            DataBaseClient service = ServiceHost.Instance;

            if (checkBox_AllModel.Checked)
            {
                //All Model
                InsertTabPage("allModel", service.CreateAllModel(), TextStyleType.cs);

            }

            if (checkBox_AllStruct.Checked)
            {
                //All Struct
                InsertTabPage("allStruct", service.CreateAllStruct(), TextStyleType.cs);
            }

            if (checkBox_AllProc.Checked)
            {
                //All proc
                InsertTabPage("AllProc", service.CreateAllProc(), TextStyleType.cs);
            }
        }

        /// <summary>
        /// 合并模式全选所有列 和 where 语句。
        /// </summary>
        /// <param name="cols"></param>
        private void ConvertColumnsToSelectAndWhere(List<Column> cols)
        {
            for (int i = 0; i < cols.Count;i++ )
            {
                Column col = cols[i];
                col.IsSelect = true;
                col.IsWhere = true;
            }
        }

        /// <summary>
        /// 默认选择主键列
        /// </summary>
        /// <param name="cols"></param>
        private void ConvertColumnsToSelectPrimaryKey(List<Column> cols)
        {
            foreach (var col in cols)
            {
                if (col.IsPrimaryKey)
                {
                    col.IsSelect = true;
                }
            }
        }

        private void InitCodeCreate(List<Column> columns,Table table)
        {
            DataBaseClient service = ServiceHost.Instance;
            bool isMerge = checkBox_CreateAll.Checked;
            
            try
            {
                if (isMerge)
                {
                    //Select & where 所有列
                    ConvertColumnsToSelectAndWhere(columns);
                }
                else
                {
                    //默认选择主键列
                    ConvertColumnsToSelectPrimaryKey(columns);
                }

                //获取功能项
                if (checkBox_Aspx.Checked)
                {
                    string code = service.CreateAspx(table);
                    if (isMerge)
                    {
                        //合并
                        code = code.Replace("{*aspxlist*}", service.CreateAspxList(table, columns));
                        code = code.Replace("{*aspxedit*}", service.CreateAspxEdit(table, columns));
                        code = code.Replace("{*aspxview*}", service.CreateAspxInfo(table, columns));
                        code = code.Replace("{*aspxserarch*}", service.CreateAspxQuery(table, columns));
                    }
                    //aspx页面
                    InsertTabPage("aspx", ConvertResult(code), TextStyleType.aspx);
                }

                if (checkBox_AspxCs.Checked)
                {
                    //aspxCs
                    string code = service.CreateAspxCs(table);
                    if (isMerge)
                    {
                        //合并输出
                        code = code.Replace("{*aspxcscmdobject*}", service.CreateAspxCsQuery(table, columns));
                        code = code.Replace("{*aspxcsedit*}", service.CreateAspxCsEdit(table, columns));
                        code = code.Replace("{*aspxcsview*}", service.CreateAspxCsInfo(table, columns));
                        code = code.Replace("{*aspxcssave*}", service.CreateAspxCsSave(table, columns));
                    }
                    InsertTabPage("aspxCs", ConvertResult(code), TextStyleType.cs);
                }

                if (checkBox_aspxdesignercs.Checked)
                {
                    //aspx.Designer.cs
                    InsertTabPage("aspx.designer.cs", ConvertResult(service.CreateAspxDesignerCs(table, columns)), TextStyleType.cs);
                }

                if (checkBox_ServiceContract.Checked)
                {
                    //service contract
                    InsertTabPage("serviceContract", ConvertResult(service.CreateServiceContract(table,columns)), TextStyleType.cs);
                }

                if (checkBox_serviceimplement.Checked)
                {
                    //Service Implement
                    InsertTabPage("serviceImplement", ConvertResult(service.CreateServiceImplement(table,columns)), TextStyleType.cs);
                }

                if (checkBox_CoreService.Checked)
                {
                    //CoreService
                    InsertTabPage("CoreService", ConvertResult(service.CreateCoreService(table)), TextStyleType.cs);
                }

                if (checkBox_DataContract.Checked)
                {
                    //datacontract
                    InsertTabPage("dataContract", ConvertResult(service.CreateDataContract(table, columns)), TextStyleType.cs);
                }


                if (checkBox_cmdObject.Checked)
                {
                    //CmdObject
                    InsertTabPage("CmdObject", ConvertResult(service.CreateServiceCmdObject(table,columns)), TextStyleType.cs);
                }

             
                if (checkBox_bussinessimplement.Checked)
                {
                    //Bussiness Implement
                    string code = service.CreateBussinessImplement(table);
                    if (isMerge)
                    {
                        //合并输出
                        code = code.Replace("{*bussinessquery*}", service.CreateServicePageList(table, columns));
                    }
                    InsertTabPage("BussinessImplement", ConvertResult(code), TextStyleType.cs);
                }
                

                if (checkBox_DataExchange.Checked)
                {
                    //dataexchange
                    InsertTabPage("dataExchange", ConvertResult(service.CreateDataExchange(table, columns)), TextStyleType.cs);
                }

                if (checkBox_IocConfig.Checked)
                {
                    //Ioc Config
                    InsertTabPage("iocConfig", ConvertResult(service.CreateIocConfig(table)), TextStyleType.xml);
                }


                if (checkBox_Edit.Checked)
                {
                    //编辑
                    InsertTabPage("aspxEdit", ConvertResult(service.CreateAspxEdit(table, columns)), TextStyleType.aspx);
                    InsertTabPage("aspxCsEdit", ConvertResult(service.CreateAspxCsEdit(table, columns)), TextStyleType.cs);
                    InsertTabPage("aspxCsSave", ConvertResult(service.CreateAspxCsSave(table, columns)), TextStyleType.cs);
                }

                if (checkBox_Query.Checked)
                {
                    //查询
                    InsertTabPage("aspxQuery", ConvertResult(service.CreateAspxQuery(table, columns)), TextStyleType.aspx);
                    InsertTabPage("aspxCsQuery", ConvertResult(service.CreateAspxCsQuery(table, columns)), TextStyleType.cs);
                    InsertTabPage("serviceCmdObject", ConvertResult(service.CreateServiceCmdObject(table, columns)), TextStyleType.cs);
                    InsertTabPage("servicePageList", ConvertResult(service.CreateServicePageList(table, columns)), TextStyleType.cs);
                }

                if (checkBox_AspxList.Checked)
                {
                    //列表
                    InsertTabPage("aspxList", ConvertResult(service.CreateAspxList(table, columns)), TextStyleType.cs);
                }

                if (checkBox_Info.Checked)
                {
                    //查看明细
                    InsertTabPage("aspxInfo", ConvertResult(service.CreateAspxInfo(table, columns)), TextStyleType.aspx);
                    InsertTabPage("aspxCsInfo", ConvertResult(service.CreateAspxCsInfo(table, columns)), TextStyleType.cs);
                }


            

       }
            catch (Exception ex)
            {
                MessageBox.Show("获取服务出现错误！");
                LogUtil.Write(ex.Message+ ex.StackTrace);
            }
        }

        /// <summary>
        /// 转换结果
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private string ConvertResult(string code)
        {
            return code.Replace("*Author*", Config.Author)
                .Replace("{*aspxlist*}", string.Empty)
                .Replace("{*aspxedit*}", string.Empty)
                .Replace("{*aspxview*}", string.Empty)
                .Replace("{*aspxserarch*}", string.Empty)
                .Replace("{*aspxcscmdobject*}", string.Empty)
                .Replace("{*aspxcsedit*}", string.Empty)
                .Replace("{*aspxcsview*}", string.Empty)
                .Replace("{*aspxcssave*}", string.Empty)
                .Replace("{*bussinessquery*}", string.Empty);
        }

        private void InsertTabPage(string Text,String Code,TextStyleType type)
        {
            ExTabPage page = new ExTabPage(Text, Code, type);
            this.tabControl_Left_First.TabPages.Add(page);
        }

        /// <summary>
        /// 清除存在选项卡
        /// </summary>
        private void ClearTabPage()
        {
            //移出已经存在的TabPage卡
            if (tabControl_Left_First.TabPages.Count > 1)
            {
                for (int i = tabControl_Left_First.TabPages.Count - 1; i > 0; i--)
                {
                    tabControl_Left_First.TabPages.RemoveAt(i);
                    //tabControl.Controls.RemoveAt(i);
                }
            }
        }

        /// <summary>
        /// 选项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 选项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OptionForm o = new OptionForm();
            if (o.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    InitTreeTable();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        /// <summary>
        /// 开发工具
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 开发工具ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DevTools.ToolForm form = new CodeBuilder.DevTools.ToolForm();
            form.Show();
        }

        /// <summary>
        /// 一键生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 一键生成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Automation.CodeBuildForm form = new CodeBuilder.Automation.CodeBuildForm();
            form.Show();
        }

        /// <summary>
        /// 关于
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox form = new AboutBox();
            form.ShowDialog();
        }

        /// <summary>
        /// 版本控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 版本控制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Automation.AssemblyForm form = new CodeBuilder.Automation.AssemblyForm();
            form.ShowDialog();
        }

        /// <summary>
        /// 代码统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 代码统计ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LineCount.MainForm cf = new LineCount.MainForm();
            cf.Show();
        }

     
      


       
    }
}
